package com.blb.edusearchservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.blb.edusearchservice.client.CourseIndexClient;
import com.blb.edusearchservice.dao.ElasticsearchDao;
import com.blb.edusearchservice.pojo.ElasticsearchEntity;
import com.blb.edusearchservice.pojo.PageEntity;
import com.blb.edusearchservice.service.ICourseIndexService;
import com.blb.pojo.Course;
import com.blb.pojo.ResponseResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CourseIndexServiceImpl implements ICourseIndexService {
    private final static String INDEX_NAME="course";
    @Resource
   private ElasticsearchDao dao;
    @Resource
    private CourseIndexClient client;
    @Override
    public void initCourseIndex() {
        try {
            if(dao.existIndex(INDEX_NAME)){
                dao.deleteIndex(INDEX_NAME);
            }
            dao.createIndex(INDEX_NAME);
            List<ElasticsearchEntity> list=new ArrayList<ElasticsearchEntity>();
            ResponseResult<List<Course>> all = client.getAll();
            all.getData().forEach(course -> {
                list.add(new ElasticsearchEntity(String.valueOf(course.getId()),course));
            });
            dao.bathData(INDEX_NAME,list);
            System.out.println("添加成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageEntity<Course> searchCoursePage(Map<String, String> map){
        try {
            int current = 1;
            int size = 10;
            Map<String,String> search = null;
            Map<String,String> sort = null;
            //读取当前行数
            if(map.containsKey("current")){
                current = Integer.valueOf(map.get("current"));
            }
            //读取分页长度
            if(map.containsKey("size")){
                size = Integer.valueOf(map.get("size"));
            }
            //读取搜索关键字
            if(map.containsKey("search")){
                search = JSON.parseObject(map.get("search"),Map.class);
            }
            //读取排序方式
            if(map.containsKey("sort")){
                sort = JSON.parseObject(map.get("sort"),Map.class);
            }
            //调用ES查询方法
            PageEntity<Course> page =null;

            page = dao.searchPageByMap(INDEX_NAME, (current -1)*size, size, search,sort, Course.class,"brief","courseName");


            return page;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void addOrUpdateCourse(Course course) throws IOException {
        dao.addData(INDEX_NAME,new ElasticsearchEntity(String.valueOf(course.getId()),course));
    }

    @Override
    public void deleteCourse(String id) throws IOException {
      dao.deleteData(INDEX_NAME,id);
    }
}
